<%@ page language="java" contentType="text/json; charset=UTF-8"
    pageEncoding="UTF-8" import="java.io.*, java.util.*, java.net.*, org.OpenGeoPortal.Download.*, org.springframework.context.*, org.springframework.context.support.*, org.springframework.web.context.support.*, org.springframework.beans.factory.* " %>
<%
	 /**
	 * This jsp should receive a POST request with an object containing 
	 * all the info needed for each layer to be downloaded.  The jsp calls a class 
	 * that handles all of the download logic.  Additionally, it checks the session
	 * variable "username" to see if the user has authenticated.  A boolean is passed
	 * to the download code.  If one has been provided, an email address is passed to the 
	 * download code to accomodate systems that email a link to the user for their layers
	 *
	 * @author Chris Barnett
	 */

	if (request.getMethod() != "POST"){
		//only allow POST requests
		response.setStatus(403);
	}

	  //do data validation here
	String layerIds = request.getParameter("layers");
	String emailAddress = request.getParameter("email");
	String bboxJoined = request.getParameter("bbox");
	String[] bbox = bboxJoined.split(",");
	String[] layers = layerIds.split("&");
	Map<String,String> layerMap = new HashMap<String,String>();
	for (int i = 0; i < layers.length; i++){
		String[] layerInfo = layers[i].split("=");
		layerMap.put(layerInfo[0], layerInfo[1]);
	}

	Boolean authenticated = false;

	try {
		String userName = session.getAttribute("username").toString();
		if (!userName.trim().isEmpty()){
			authenticated = true;
		}
	} catch (NullPointerException e){
		//
	}

	ApplicationContext injector = WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext());
	DownloadHandler downloadHandler = (DownloadHandler) injector.getBean("downloadPackager");
	downloadHandler.setLocallyAuthenticated(authenticated);
	downloadHandler.setReplyEmail(emailAddress);
	downloadHandler.requestLayers(layerMap, bbox);
	
	//return a link to the zip file, or info to create link  
	response.getWriter().write(downloadHandler.getJsonResponse());
	
%>
